import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/tokenStore'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home', 
      component: HomeView,
      children: [
        {
          path: '/ingredients',
          name: 'ingredients',
          component: () => import('../views/ingredients/index.vue'),
        },
        {
          path: '/dishes',
          name: 'dishes',
          component: () => import('../views/dishes/index.vue'),
        },
        {
          path: '/prepare',
          name: 'prepare',
          component: () => import('../views/prepare/index.vue'),
        },
        {
          path: '/order',
          name: 'order',
          component: () => import('../views/order/index.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/login/index.vue'),
    },
  ],
})
router.beforeEach((to, from) => {
  const tokenStore = useTokenStore()
  if (to.path === '/login') {
    if (tokenStore.TOKEN) {
      return {path: '/'}
    }
  } else {
    if (!tokenStore.TOKEN) {
      ElMessage.error('下面的区域,登录之后再来探索吧')
      return {path: '/login', query: {dest: to.fullPath}}
    }
  }
})
export default router
